package com.hngy.xpq.fileiodemo;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.hngy.xpq.fileiodemo.tool.FileStorage;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button setFile, getFile, setSDFile, getSDFile, showFile;
    private EditText fileName, fileText;
    private TextView showText;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 获取权限
        FileStorage.verifyStoragePermissions(MainActivity.this);
        // 初始化
        init();
    }

    private void init() {
        // 初始化文件内容
        // FileStorage.createFile();
        // Button
        setFile = findViewById(R.id.setFile);
        getFile = findViewById(R.id.getFile);
        setSDFile = findViewById(R.id.setSDFile);
        getSDFile = findViewById(R.id.getSDFile);
        showFile = findViewById(R.id.showFile);
        // EditText
        fileName = findViewById(R.id.fileName);
        fileText = findViewById(R.id.fileText);
        showText = findViewById(R.id.showText);
        // 触发事件
        setFile.setOnClickListener(this);
        getFile.setOnClickListener(this);
        setSDFile.setOnClickListener(this);
        getSDFile.setOnClickListener(this);
        showFile.setOnClickListener(this);
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        String file_name = fileName.getText().toString();
        String file_text = fileText.getText().toString();
        String text = "";
        switch (v.getId()) {
            case R.id.setSDFile:
                FileStorage.saveSDFile(this, file_name, file_text);
                break;
            case R.id.getSDFile:
                text = FileStorage.readSDFile(this, file_name);
                showText.setText("结果：" + text);
                break;
            case R.id.setFile:
                FileStorage.saveFile(this, file_name, file_text);
                break;
            case R.id.getFile:
                text = FileStorage.readFile(this, file_name);
                showText.setText("结果：" + text);
                break;
            case R.id.showFile:
                FileStorage.listFiles(this);
                break;
        }
    }


}